package me.itsoo.artemis.framework.core.enumer;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import me.itsoo.artemis.framework.core.collect.Kv;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Helper
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/5/1
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Helper extends ClassValue<Map<Object, Object>> {

    private static final Helper INSTANCE = new Helper();

    /**
     * 创建实例
     *
     * @param type Class
     * @return Map
     */
    public static Map<Object, Object> create(Class<? extends Enum<?>> type) {
        return INSTANCE.get(type);
    }

    @Override
    protected Map<Object, Object> computeValue(Class<?> type) {
        final Map<Object, Object> map = new HashMap<>(16);
        final List<Kv<Integer, String>> coll = new LinkedList<>();

        for (Field field : type.getDeclaredFields()) {
            if (field.isEnumConstant()) {
                addValue(map, field, coll);
            }
        }

        map.put(VirtualEnum.ENUM_ALL, coll);
        return Collections.unmodifiableMap(map);
    }

    private void addValue(Map<Object, Object> map, Field field, List<Kv<Integer, String>> coll) {
        try {
            final Object constant = field.get(null);
            final Ev ev = field.getAnnotation(Ev.class);

            map.put(ev.code(), constant);
            map.put(constant, ev.label());
            map.put(field.getName() + VirtualEnum.ENUM_NAME, ev.code());

            coll.add(new Kv<>(ev.code(), ev.label()));
        } catch (IllegalAccessException ignore) { // NOSONAR
        }
    }
}
